package com.frank.gateway.exception;

import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.frank.common.entity.Result;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/8
 * @description
 */
@Slf4j
@Component
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    @NonNull
    public Mono<Void> handle(ServerWebExchange serverWebExchange,@NonNull Throwable throwable) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        int code;
        String message;
        if (throwable instanceof SaTokenException) {
            code = 401;
            message = "用户无权限！";
            log.error(Arrays.toString(throwable.getStackTrace()));
        }else{
            code = 500;
            message = "服务器错误！";
            log.error(Arrays.toString(throwable.getStackTrace()));
        }
        Result<Object> result = Result.fail(code, message);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(Mono.fromSupplier(()->{
            DataBufferFactory bufferFactory = response.bufferFactory();
            byte[] bytes;
            try {
                bytes = objectMapper.writeValueAsBytes(result);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            return bufferFactory.wrap(bytes);
        }));
    }
}
